package com.sptpc.learnspring.service.impl;

import com.sptpc.learnspring.controller.request.SearchOrderRequest;
import com.sptpc.learnspring.model.Order;
import com.sptpc.learnspring.repository.OrderRepository;
import com.sptpc.learnspring.service.IOrderService;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;

@Service
public class OrderServiceImpl implements IOrderService {
    @Autowired
    OrderRepository orderRepository;
    @Override
    public Order addNewOrder(Order newOrder) {
        // 从数据安全的角度，不能直接使用前端统计的总价
        BigDecimal totalPrice = newOrder.getItems().stream()
                .map(drink -> drink.getPrice().getAmount())
                .reduce(BigDecimal.ZERO, ((total, price) -> total.add(price)));
        newOrder.setPrice(Money.of(CurrencyUnit.of("CNY"), totalPrice));
        return orderRepository.saveAndFlush(newOrder);
    }

    @Override
    public Page<Order> searchOrders(SearchOrderRequest condition, PageRequest page) {
        LocalDate start = condition.getStartDate();
        LocalDate end = condition.getEndDate();
        Integer state = condition.getState();
        Page<Order> orders = orderRepository
                .findOrdersByCreateTimeBetweenOrState(start, end, state, page);
        return orders;
    }

}
